package transaction.lcn.storage.service;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import tk.mybatis.mapper.entity.Example;
import transaction.lcn.storage.mapper.StorageTblMapper;
import transaction.lcn.storage.model.StorageTbl;

import javax.sql.DataSource;
import java.util.List;

@Service
@Slf4j
public class StorageService {


    @Autowired
    private StorageTblMapper storageMapper;
    @Autowired
    private DataSource dataSource;

    //    @LcnTransaction //分布式事务注解
//    @Transactional //本地事务注解
    public void deduct(String commodityCode, int count) {
        // 并发情况会有数据不准确问题
        StorageTbl storage = findByCommodityCode(commodityCode);
        assert storage != null;
//        storage.setCount(storage.getCount() - count);
//        storageMapper.updateByPrimaryKeySelective(storage);
        // 单行sql执行
        int row = storageMapper.updateByPrimaryKeyCustom(storage.getId(), count);
        if (row < 1) {
            log.error("库存不够了 {},{}", commodityCode, count);
            throw new RuntimeException("库存不够了" + commodityCode + ":" + count);
        }
    }

    private StorageTbl findByCommodityCode(String commodityCode) {
        Example example = new Example(StorageTbl.class);
        example.createCriteria().andEqualTo("commodityCode", commodityCode);
        List<StorageTbl> list = storageMapper.selectByExample(example);
        return CollectionUtils.isEmpty(list) ? null : list.get(0);
    }

}
